<?php

namespace app\api\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\api\controller\Pay;
use think\log;

use linghuo\v2\Linghuo as linghuo2;
use linghuo\Linghuo as linghuo;
use app\common\model\userIdCard;
use app\admin\model\UserWithdraw;
use app\admin\model\Recharge;
use app\common\model\MoneyLog;
use app\admin\model\share\ShareUser;
use think\Db;

class Tmp extends Command
{
    protected function configure()
    {
        $this->setName('tmp')->setDescription('tmp');
    }

    protected function execute(Input $input, Output $output)
    {
       // $this->withdrawError( $input,  $output);
       // $this->updateRecharge( $input,  $output);
        $this->updateMemberId();
        // $this->realnameRepair();
        // $this->updateUserWithdraw();
        echo "ok".date('Y-m-m H:i:s') . PHP_EOL;
    }

    protected function updateRecharge(Input $input, Output $output)
    {
        $output->writeln('updateRecharge Crontab job start...'.date('Y-m-d H:i:s'));
        $output->writeln('---------------------------------------------------');
        $userids = MoneyLog::where('type','=',8)
            ->group('createtime,user_id')
            ->field('user_id')
            ->distinct(true)
            ->having('count(id) > 1')
            // ->fetchSql(true)
            ->select();
        foreach ($userids as $value) {
            $moneyLogs = MoneyLog::where('user_id','=',$value['user_id'])->order('createtime asc')->select();
            $time = 0;
            $num = 0;
            foreach ($moneyLogs as $key => $log) {
                if ($time == $log->createtime) {
                    $num += $log->money;
                    $output->writeln('updateRecharge 记录重复删除...'. json_encode($log,JSON_UNESCAPED_UNICODE) );

                    \db('user_money_log_del')->insert([
                        'id' => $log->id,
                        'user_id' => $log->user_id,
                        'money' => $log->money,
                        'before' => $log->before,
                        'after' => $log->after,
                        'memo' => $log->memo,
                        'createtime' => $log->createtime,
                        'type' => $log->type,
                        'mobile' => $log->mobile,
                    ]);
                    $log->delete();
                    continue;
                }
                $time = $log->createtime;
                $log->before -= $num;
                $log->after -= $num;
                $output->writeln('updateRecharge 记录修改...'.json_encode($log,JSON_UNESCAPED_UNICODE) );
                $log->save();
                // var_dump($log);exit;
            }
            $output->writeln('updateRecharge user_id...'.$log['user_id'] . '..减少余额：'.$num);
            $output->writeln('---------------------------------------------------');
            ShareUser::where('user_id','=',$log['user_id'])->setDec('price',$num);
            $user = ShareUser::where('user_id','=',$log['user_id'])->find();
            $output->writeln('剩余：'. $user['price']);
        }
        $output->writeln('updateRecharge Crontab job end...'.date('Y-m-d H:i:s'));
    }
    /**
     * [updateMemberId 更新系统ID]
     * @since  2022-10-24
     * @return [type]     [description]
     */
    protected function updateMemberId()
    {
        set_time_limit(0);
        $i =0;
        while (true) {
            //存在，就修改
            // userIdCard::where('user_id','in',$userids)->update(['memberId'=>'']);
            $idCardDatas = userIdCard::limit($i*100,100)
            // $idCardDatas = userIdCard::where('systemId','=','')
                // ->select();
            // $idCardDatas = userIdCard::where('user_id','=',11235)->select();
            // $idCardDatas = userIdCard::whereNull('memberId')
            // $idCardDatas = userIdCard::where('user_id','=','11246')
                // ->whereOr('memberId','=','')
                // ->fetchSql(true)
                ->select();
            if (!$idCardDatas) {
                break;
            }
                $i++;
            // var_dump($idCardDatas);exit;
            foreach ($idCardDatas as $k => $idCardData) {
                echo $k . PHP_EOL;
                // 实名
                $res1 = (new linghuo)->query(linghuo::QUERY_TYPE_3,'',$idCardData->idCard);
                $res2 = (new linghuo2)->getsystemid(Linghuo2::GET_SYSTEM_ID_TYPE_3,$idCardData->idCard);
                $bool = false;
                if ($res2['code'] === 1 && $res2['data']['result']['systemId']) {
                    $idCardData->systemId = $res2['data']['result']['systemId'];
                    $bool = true;
                }
                if ($res1['code'] === 1 && $res1['data']['result']['memberId']) {
                    $idCardData->memberId = $res1['data']['result']['memberId'];
                    $bool = true;
                }
                if ($bool) {
                    $idCardData->save();
                }else{
                    if (empty($idCardData->name) || empty($idCardData->idCard) || empty($idCardData->phone) || empty($idCardData->imgIdCardFront) || empty($idCardData->imgIdCardBack)  ) {
                        $idCardData->delete();
                        // echo ('updateMemberId-name：不存在'.var_export($idCardData->toArray() ,true));
                        log::record('updateMemberId-name：不存在'.var_export($idCardData->toArray() ,true),'thirdpay');
                        continue;
                    }
                    $res = (new linghuo2)->register($idCardData->name,$idCardData->idCard,$idCardData->phone,$idCardData->imgIdCardFront,$idCardData->imgIdCardBack);
                    // var_dump($res);
                    if ($res['code'] === 1 && $res['data']['result']['systemId']) {
                        if ($res['data']['result']['memberId'] ) {
                            $idCardData->memberId = $res['data']['result']['memberId'];
                        }
                        if ($res['data']['result']['systemId'] ) {
                            $idCardData->systemId = $res['data']['result']['systemId'];
                        }
                        $idCardData->save();
                    }else{
                        // $idCardData->delete();
                        // echo ('updateMemberId-name：注册失败'.var_export($idCardData->toArray() ,true).var_export($res ,true),'thirdpay');
                        log::record('updateMemberId-name：注册失败'.var_export($idCardData->toArray() ,true).var_export($res ,true),'thirdpay');
                        continue;
                    }
                }
                // 会员信息
                $userinfo = (new linghuo2)->query($idCardData->systemId);
                if (empty($userinfo['data']['result'])) {
                    continue;
                }
                if ($userinfo['data']['result']['name'] != $idCardData->name) {
                    $idCardData->name = $userinfo['data']['result']['name'];
                     $idCardData->save();
                }
                //更新绑卡
                if (!empty($idCardData->phone) && !empty($idCardData->bankNo) && !empty($idCardData->cardNo) && !empty($idCardData->bankPhone)) {
                    $updateRes = (new linghuo2)->update($idCardData['systemId'],$idCardData->bankNo,$idCardData->cardNo,$idCardData->bankPhone);
                    if ($updateRes['code'] !== 1) {
                        // echo ('updateMemberId-name：绑卡更新失败'.var_export($idCardData->toArray() ,true));
                        log::record('updateMemberId-name：绑卡更新失败'.var_export($idCardData->toArray() ,true),'thirdpay');
                        // 反向修改
                        
                    }else{
                        //修改成功
                        continue;
                    }
                }
                // 反向修改
                if ($userinfo['data']['result']['bankNo']) {
                    $idCardData->bankNo = $userinfo['data']['result']['bankNo'];
                }
                if ($userinfo['data']['result']['cardNo']) {
                    $idCardData->cardNo = $userinfo['data']['result']['cardNo'];
                }
                if ($userinfo['data']['result']['bankPhone']) {
                    $idCardData->bankPhone = $userinfo['data']['result']['bankPhone'];
                }
                if ($userinfo['data']['result']['bankName']) {
                    $idCardData->bankName = $userinfo['data']['result']['bankName'];
                }
                $idCardData->save();
                // echo ('updateMemberId-name：已经绑卡'.var_export($idCardData->toArray() ,true));
                log::record('updateMemberId-name：已经绑卡'.var_export($idCardData->toArray() ,true),'thirdpay');
                // echo $res['msg'].'<br />';
            }
        }
        
    }
    /**
     * [updateUserWithdraw 提现修复]
     * @since  2022-10-24
     * @return [type]     [description]
     */
    protected function updateUserWithdraw()
    {
        set_time_limit(0);
        //存在，就修改
        $idCardDatas = userIdCard::select();
        // $idCardDatas = userIdCard::whereNull('memberId')
        // $idCardDatas = userIdCard::where('user_id','=','12687')
            // ->whereOr('memberId','=','')
            // ->fetchSql(true)
            // ->select();
        foreach ($idCardDatas as $idCardData) {
            if (empty($idCardData->memberId)||empty($idCardData->systemId)||empty($idCardData->name)||empty($idCardData->idCard)) {
                continue;
            }
            $saveData = [
                'memberId'=>$idCardData->memberId,
                'systemId'=>$idCardData->systemId,
                'memberName'=>$idCardData->name,
                'idCard'=>$idCardData->idCard,
            ];
            // UserWithdraw::where('user_id','=',$idCardData->user_id)->where('payType','in',[0,3])->where('auditStatus','=',1)->update($saveData);
            UserWithdraw::where('user_id','=',$idCardData->user_id)->where('payType','in',[0,3])->where('auditStatus','in',[0,1])->update($saveData);
        }
    }
    /**
     * [realnameRepair 实名修复]
     * @since  2022-10-16
     * @return [type]     [description]
     */
    protected function realnameRepair()
    {
        set_time_limit(0);
        //存在，就修改
        $idCardDatas = userIdCard::select();
        // $idCardDatas = userIdCard::whereNull('systemId')
            // ->whereOr('systemId','=','')
            // ->fetchSql(true)
            // ->select();
        foreach ($idCardDatas as $value) {
            $bool = false;
            $res1 = (new linghuo)->query(linghuo::QUERY_TYPE_3,'',$value->idCard);
            $res2 = (new linghuo2)->getsystemid(Linghuo2::GET_SYSTEM_ID_TYPE_3,$value->idCard);
            if ($res2['code'] === 1 && $res2['data']['result']['systemId']) {
                $value->systemId = $res2['data']['result']['systemId'];
                $bool = true;
            }
            if ($res1['code'] === 1 && $res1['data']['result']['memberId']) {
                $value->memberId = $res2['data']['result']['memberId'];
                $bool = true;
            }

            if ($bool) {
                $value->save();
            }else{
                if (empty($value->name) || empty($value->idCard) || empty($value->phone) || empty($value->imgIdCardFront) || empty($value->imgIdCardBack)  ) {
                    continue;
                }
                $res = (new linghuo2)->register($value->name,$value->idCard,$value->phone,$value->imgIdCardFront,$value->imgIdCardBack);

                if ($res['code'] === 1) {
                    if ($res['data']['result']['systemId']) {
                        $value->systemId = $res['data']['result']['systemId'];
                    }
                    if ($res['data']['result']['memberId']) {
                        $value->memberId = $res['data']['result']['memberId'];
                    }
                    $value->save();
                }
            }

            
            var_dump($value->idCard);
            echo $res1['msg'].'<br />';
            
            echo $res['msg'].'<br />';
        } 
    }

    /**
     * [repay 重新支付  只使用  感谢有您]
     * @since  2022-11-09
     * @return [type]     [description]
     */
    public function repay()
    {
        $today = date('Ymd');
        $UserWithdrawmodel = new \app\admin\model\UserWithdraw;
        $values = ['payType'=>$UserWithdrawmodel::PAY_TYPE_0];
        // 重新支付
        if (isset($values['payType'])&& (time() < strtotime($today.'090000') || time() > strtotime($today.'180000')) ) {
            return ;
            // $this->error(__('提现审核请于10：00~18：00操作'));
        }
        $values['auditUserId'] = '1';
        $values['auditUsername'] = 'system';
        $values['auditTime'] = time();
        $where['payType'] = $UserWithdrawmodel::PAY_TYPE_3;//支付失败的
        $where['auditTime'] = ['gt',strtotime($today)];//今天审核的
        $ids = $UserWithdrawmodel->where($where)
            // ->fetchSql(true)
            ->column('id');
        if (empty($ids)) {
            return;
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $UserWithdrawmodel
                ->where('id', 'in', $ids)
                // ->where($where)
                ->lock(true)
                // ->fetchSql(true)
                ->select();
            foreach ($list as $item) {
                // var_dump($item->user_id);
                // Db::commit();exit;
                $shareUserOne = \app\admin\model\share\ShareUser::where('user_id', '=', $item->user_id)->find();
                // 用户注销
                if (!$shareUserOne) {
                    continue;
                } 
                $price = floatval($shareUserOne->price);
                // 余额不足
                if ($price < $item->money) {
                    continue;
                }
                // 锁定余额
                $shareUserOne->lock_money($shareUserOne, $item['money']);
                // 如果为重新支付
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
        }
    }
}
